package com.haha.community;

import com.haha.community.entiy.DiscussPost;
import com.haha.community.entiy.Page;
import com.haha.community.entiy.User;
import com.haha.community.service.DiscussPostService;
import com.haha.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController {
    @Autowired
    UserService userService;
    @Autowired
    DiscussPostService discussPostService;

    @RequestMapping(path = "/index",method = RequestMethod.GET)
    public String handIndex(Model model, Page page){
        //进行页码相关的设置,方法调用的时候会将参数上的对象装入model中
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("/index");
        List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit());
        List<Map<String,Object>> list = new ArrayList<>();
        //将list返回，里面装好多map，每个map里面有user和post
        if (discussPosts!=null){
            for (DiscussPost discussPost:discussPosts){
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("post",discussPost);
                User user = userService.findUserById(discussPost.getUserId());
                hashMap.put("user",user);
                list.add(hashMap);
            }
        }
        model.addAttribute("discussPost",list);
        return "/index";
    }
}
